﻿namespace HxMSimulator
{
    using System.Linq;
    using FitnessTracker.Packet;

    public static class CRCCalculator
    {
        public static void SetCRC(byte[] buffer)
        {
            buffer[HxMPacketStructure.CRCOffset] = CalculateCRC(buffer);
        }

        private static byte CalculateCRC(byte[] buffer)
        {
            var currentChecksum = (byte)0;

            for (var index = HxMPacketStructure.FirmwareIDOffset; index < HxMPacketStructure.CRCOffset; index++)
            {
                currentChecksum = ChecksumPushByte(currentChecksum, buffer.ElementAt(index));
            }

            return currentChecksum;
        }

        private static byte ChecksumPushByte(byte currentChecksum, byte newByte)
        {
            currentChecksum ^= newByte;
            for (var index = 0; index < 8; ++index)
            {
                if ((currentChecksum & 1) == 1)
                {
                    currentChecksum = (byte)(currentChecksum >> 1 ^ 140);
                }
                else
                {
                    currentChecksum >>= 1;
                }
            }

            return currentChecksum;
        }
    }
}
